/*
 * @Description: 新增工单信息
 * @Version: V1.0.0
 * @Autor: CHY
 * @Date: 2022-04-05 16:09:21
 * @LastEditors: CHY
 * @LastEditTime: 2022-04-09 18:25:25
 */
import React, { useState, useEffect } from 'react';
import WangEditor from '@twp0217/react-wangeditor';
import { Form, Input, Button, Select, DatePicker, Modal, message, Space, Upload } from 'antd';
import PubSub from 'pubsub-js';
import {
    CheckCircleFilled,
    PlusSquareFilled
} from '@ant-design/icons';
import moment from 'moment';

import AddClientModal from './addClientModle';
import CustomOptions from './customOptions'
import FastSelect from './fastSelect';

import './index.css'
import '../../button.css'
import '../../modal.css'

const AddOrderInfo = (props) => {
    const [FormRef3] = Form.useForm()
    // const addRef = useRef(null)
    const [clientInfodata, setClientInfo] = useState({})//工单类名数据
    const [clientlist, setClienList] = useState([//定义联系人数组
        { id: 0, name: 'xxxx', tel: 1235615452 }
    ])
    let arrList = [{ id: clientlist.length + 1, name: '', tel: '' }]
    let fnHeadle = null
    const { Option } = Select;
    const onFinish = (values) => {
        console.log('Success:', values);
    };
    const [modalData, setModalData] = useState([//定义模态框数据
        { id: 1, modalName: 'addOrderCate', flage: false },
        { id: 2, modalName: 'transport', flage: false },
        { id: 3, modalName: 'assigned', flage: false },
        { id: 4, modalName: 'travelContact', flage: false }
    ])
    const [sendData, setsendData] = useState([//定义模态框数据(初始化)
        { id: 0, sendName: '售后工单' },
        { id: 1, sendName: '订单配送' },
    ])
    const [transportData, setTransportData] = useState([//定义模态框数据(初始化)
        { id: 0, sendName: '火车' },
        { id: 1, sendName: '汽车' },
    ])
    // 定义快速选择数据接收数据
    const [assignedData, setAssigneData] = useState([
        { id: 1, department: '总经办', jobTitle: ['超级管理员', '员工', '345'], flage: false },
        { id: 2, department: '财务部	', jobTitle: null, flage: false },
        { id: 3, department: '业务一部', jobTitle: null, flage: false },
        { id: 4, department: '业务二部', jobTitle: null, flage: false },
        { id: 5, department: '渠道招商部	', jobTitle: null, flage: false },
        { id: 6, department: '营销部	', jobTitle: [123], flage: false },
        { id: 7, department: '采购部', jobTitle: null, flage: false },
        { id: 8, department: '客服部', jobTitle: null, flage: false }
    ])
    const [assigineArr, setAssigineeArr] = useState([])


    //#region INFO:自定义modal框封装####################################################
    let ResArr = []
    let ResArr2 = []
    let clearnheadle = null
    let SaveGetArr1 = []//定义发布快速选择数据接收数组
    let SaveGetArr2 = []//定义发布快速选择数据接收数组(差旅联系人)

    /**
     * @description: 显示与隐藏模态框函数
     * @param {*默认事件对象：any} e
     * @param {*模态框数据默认id:Number} id
     * @param {*模态框开关s为打开h为隐藏：string} sw
     * @param {*对应模态框名，用来区分不同模态框：string} modalName12
     * @return {*}
     * @author: CHY
     */
    function modoalSH(e, id, sw, modalName12) {
        console.log("modalName", modalName12);
        let arr = []
        modalData.forEach(item => {
            if (item.id === id && item.modalName === modalName12) {
                if (sw === 's') {
                    item.flage = true
                } else {
                    item.flage = false
                }
                arr.push(item)
            } else {
                arr.push(item)
            }
        });
        setModalData(arr)
        // console.log("modalName", modalName12);
        if (modalName12 === 'assigned') {//清空指派人员输入框
            FormRef3.setFieldsValue({
                assignPerson: ''
            })
            // console.log("modalName", modalName12);
            // setAssigineeArr([])
            // SaveGetArr = []//定义发布快速选择数据接收数组
        }
        // console.log(arr);
    }
    /**
     * @description: 
     * @param {*默认为事件函数} e
     * @param {*子组件传来的数据} Resdata
     * @param {*子组件传来触发modal框名，用来区分} modalcate
     * @param {*清空子组件输入的事件函数} fn
     * @return {*}
     * @author: CHY
     */
    function headleSendData(e, Resdata, modalcate, fn) {
        console.log('子组件传来触发modal框名用来区分', e, Resdata, modalcate, fn);
        if (Resdata === null || Resdata === '') {
            // console.log('新增工单信息Resdata,modalcate', Resdata);
            info('输入/传入不能为空！')
        } else {
            // console.log('新增工单信息Resdata,modalcate', Resdata);
            modalcate === 'addOrderCate' ? ResArr = [{ id: sendData.length + parseInt(Math.random() * 100000000), sendName: Resdata }] : ResArr = []//新增工单信息接收数据处理
            modalcate === 'transport' ? ResArr2 = [{ id: transportData.length + parseInt(Math.random() * 100000000), sendName: Resdata }] : ResArr2 = []//交通方式接收数据处理
            modalcate === 'assigned' ? Resdata.flage ? SaveGetArr1.push(Resdata.data) : SaveGetArr1 = SaveGetArr1.filter(item => {//指派人员收数据处理
                return item !== Resdata.data
            }) : SaveGetArr1 = []
            modalcate === 'travelContact' ? Resdata.flage ? SaveGetArr2.push(Resdata.data) : SaveGetArr2 = SaveGetArr2.filter(item => {//指派人员收数据处理
                return item !== Resdata.data
            }) : SaveGetArr2 = []
            // console.log('新增工单信息transport', SaveGetArr1);

            clearnheadle = fn//将事件函数赋值
        }
    }

    /**
     * @description: 关闭保存处理函数(addOrderCate,transport，travelContact，assigned)
     * @param {*对应模态框名} data
     * @return {*}
     * @author: CHY
     */
    function saveAddOrdercata(data) {
        console.log(ResArr, ResArr2);
        //关闭保存时处理新增类型数据
        if (data === 'addOrderCate') {
            ResArr.length === 0 ? info('输入不能为空！') : setsendData([...sendData, ...ResArr])
            // ResArr = []
            if (ResArr.length === 0) {
                return
            } else {
                modoalSH('e', 1, 'h', 'addOrderCate')
            }
        }
        //关闭保存时处理交通方式
        if (data === 'transport') {
            // console.log("transportData");
            // console.log('transport', ResArr2);
            ResArr2.length === 0 ? info('输入不能为空！') : setTransportData([...transportData, ...ResArr2])
            // ResArr = []
            if (ResArr2.length === 0) {
                return
            } else {
                modoalSH('e', 2, 'h', 'transport')
            }
        }
        //关闭保存时处理指派人员数据
        if (data === 'assigned') {
            SaveGetArr1.length === 0 ? info('输入不能为空！') : setAssigineeArr(SaveGetArr1)
            modoalSH('e', 3, 'h', 'assigned')
            // console.log('新增工单信息transport', SaveGetArr1);
            FormRef3.setFieldsValue({
                assignPerson: SaveGetArr1
            })
            SaveGetArr1 = []
        }
        //关闭保存时处理差旅联系人数据
        if (data === 'travelContact') {
            SaveGetArr2.length === 0 ? info('输入不能为空！') : setAssigineeArr(SaveGetArr1)
            modoalSH('e', 4, 'h', 'travelContact')
            // console.log('新增工单信息transport', SaveGetArr1);
            FormRef3.setFieldsValue({
                travelClien: SaveGetArr2
            })
            SaveGetArr1 = []
        }

        if (clearnheadle !== null && clearnheadle !== undefined) {
            clearnheadle()
        }


    }

    /**
     * @description: 关闭工单模态框处理函数(addOrderCate,transport，assigned，travelContact)
     * @param {*对应模态框名} data
     * @return {*}
     * @author: CHY
     */
    function colseAddOrdercata(data) {
        // console.log(ResArr);
        if (data === 'addOrderCate') {
            ResArr.length === 0 ? modoalSH('e', 1, 'h', 'addOrderCate') : setsendData([...sendData, ...ResArr])
            modoalSH('e', 1, 'h', 'addOrderCate')
        }
        if (data === 'transport') {
            ResArr2.length === 0 ? modoalSH('e', 2, 'h', 'transport') : setTransportData([...transportData, ...ResArr2])
            modoalSH('e', 2, 'h', 'transport')
        }
        if (data === 'assigned') {
            modoalSH('e', 3, 'h', 'assigned')
        }
        if (data === 'travelContact') {
            modoalSH('e', 4, 'h', 'travelContact')
        }
    }

    //#endregion ########################################################################
    message.config({
        maxCount: 1
    })
    //#region INFO:组件默认模态框处理函数*************************************************
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    const [isModalVisible, setIsModalVisible] = useState(false);

    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleOk = (e) => {
        setIsModalVisible(false);
        e.stopPropagation()
    };
    //职位信息弹窗
    const info = (str) => {
        message.error(str);
    };
    //处理职位信息数据
    const handleCancel = (e) => {
        // setIsModalVisible(false);//关闭modal框
        // console.log('clientlist', arrList[0], arrList[0].tel, arrList[0].name);
        if (arrList[0] === undefined || arrList[0].tel === '' || arrList[0].name === '' || arrList[0].tel === undefined || arrList[0].name === undefined) {
            info('客户名和电话号码不能为空！')
            return
        } else {
            setClienList([...clientlist, ...arrList])
            // console.log('clientlist', arrList[0]);
            setIsModalVisible(false);//关闭modal框
            fnHeadle()
        }
    };
    //#endregion /*******************************************************************/

    /**保存处理(data职位位联系人信息) */
    function saveHandleCancel(data, fn) {
        fnHeadle = fn
        // e.stopPropagation()
        const { clientPerson, tel } = data
        arrList = [{ id: clientlist.length + 1, name: clientPerson, tel: tel }]
    }
    /*  // 返回重选
     function exitHeadle() {
         // console.log('@@@@@', clientInfodata);
         clientInfodata.handleCancel()
 
     } */
    function exitHandleCancel() {
        setIsModalVisible(false);
    }
    //新增联系人
    function addClient(e) {
        // console.log("@@@");
        e.stopPropagation()
        showModal()
    }

    //文件上传
    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //DOING:onchange事件
    let timer3 = null
    function onChangeHeadle() {
        clearTimeout(timer3)
        timer3 = setTimeout(() => {
            console.log("###onChangeHeadle###", getFormdata());
            PubSub.publish('modifiDataAll', getFormdata())
        }, 500)
    }
    //拿取表单数据
    function getFormdata() {
        const dataAll = FormRef3.getFieldsValue()

        return dataAll
    }
    //删除后发布
    useEffect(() => {
        //订阅自定义选项删除
        PubSub.subscribe('delateData', (_, data) => {//订阅自定义选项删除
            // console.log('新增工单信息data', data);
            if (data.cateName === '工单类型') {
                setsendData(data.dataArr)
            }
            if (data.cateName === '交通方式') {
                setTransportData(data.dataArr)
            }
        })
        return () => {

            PubSub.unsubscribe('delateData') //销毁订阅 防止多次触发 
        }
    }, []);
    //DOING:生命周期 ，拿取初次信息
    useEffect(() => {
        // 订阅新增工单类型名
        PubSub.subscribe('modifiInfo', (_, data) => {
            FormRef3.resetFields();
            setClientInfo(data)
            FormRef3.setFieldsValue({
                clientName: data[0].clientName,
                clienPerson: data[0].clientPerson,
                orderCate: data[0].orderCate,
                assignPerson: data[0].businessTraveller,
                beginTime: moment(data[0].staringTime, 'YYYY-MM-DD HH:mm:ss'),
                endTime: moment(data[0].endTime, 'YYYY-MM-DD HH:mm:ss'),
                travelClien: data[0].transportation,
                transport: data[0].businessTraveller,
                text: data[0].workSpecification,
            })
            console.log('modifiInfo', data, data[0].endTime);
        })
        return () => {
            // PubSub.unsubscribe(add2)
            PubSub.unsubscribe('modifiInfo') //销毁订阅 防止多次触发 
        }

    }, []);


    //时间输入框
    function range(start, end) {
        const result = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }
    function disabledDate(current) {
        // Can not select days before today and today
        return current && current < moment().endOf('day');
    }

    function disabledDateTime() {
        return {
            disabledHours: () => range(0, 24).splice(4, 20),
            disabledMinutes: () => range(30, 60),
            disabledSeconds: () => [55, 56],
        };
    }
    return (
        <div className='addOrderInfo-contanier'>
            <h3>新增工单信息</h3>
            <div className='addOrderInfo-box'>
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{
                        remember: true,
                        clienPerson: '',
                        transport: '请选择',
                        orderCate: '请选择'
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={FormRef3}
                >
                    <Form.Item label="客户名称" rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Form.Item noStyle name="clientName">
                            <Input bordered={false} className='addOrderInfo-form-name' />
                        </Form.Item>
                        {/* <Form.Item noStyle >
                            <Button type='primary' className='btn-bgc-6' size='small' onClick={exitHeadle}>重选</Button>
                        </Form.Item> */}
                    </Form.Item>
                    <Form.Item label="关联信息" className='addOrderInfo-form-info' >
                        <Space>
                            <Form.Item noStyle >
                                <Button name="associatedInfo" type='primary' size='small' className='btn-bgc-14'>基本资料</Button>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-14'>跟单(0)</Button>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-14'>定单(0)</Button>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-14'>合同(0)</Button>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-14'>售后(0)</Button>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-14'>收支(0)</Button>
                            </Form.Item>
                        </Space>
                    </Form.Item>
                    <Form.Item label="客户联系人" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Space>
                            <Form.Item noStyle name="clienPerson" >
                                <Select style={{ width: 150 }} onChange={onChangeHeadle}>
                                    {
                                        clientlist.map(item => {
                                            return (
                                                <Option value={item.id} key={item.id}>{item.name}-{item.tel}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-15' onClick={addClient}>
                                    <PlusSquareFilled />新增
                                </Button>
                            </Form.Item>
                        </Space>
                    </Form.Item>
                    <Form.Item label="工单类型" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Space>
                            <Form.Item noStyle name="orderCate">
                                <Select name="orderCate" style={{ width: 100 }} onChange={onChangeHeadle}>
                                    {
                                        sendData.map(item => {
                                            return (
                                                <Option value={item.sendName} key={item.id}>{item.sendName}</Option>
                                            )
                                        })
                                    }
                                    {/* <Option value="USD">售后工单</Option>
                            <Option value="CNY">¥</Option> */}
                                </Select>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-15' onClick={(e) => modoalSH(e, 1, 's', "addOrderCate")}><PlusSquareFilled />新增</Button>
                            </Form.Item>
                        </Space>
                    </Form.Item>
                    <Form.Item label="指派人员" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Space>
                            <Form.Item noStyle name="assignPerson">
                                <Input bordered={false} disabled={true} style={{ width: 150, background: '#ccc' }} onChange={onChangeHeadle} />
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-15' onClick={(e) => modoalSH(e, 3, 's', "assigned")}><CheckCircleFilled />选择指派人员</Button>
                            </Form.Item>
                        </Space>
                    </Form.Item>
                    <Form.Item name="beginTime" label="起始时间" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <DatePicker onChange={onChangeHeadle}
                            format="YYYY-MM-DD HH:mm:ss"
                            disabledDate={disabledDate}
                            disabledTime={disabledDateTime}
                            showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                        />
                    </Form.Item>
                    <Form.Item name="endTime" label="结束时间" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <DatePicker onChange={onChangeHeadle}
                            format="YYYY-MM-DD HH:mm:ss"
                            disabledDate={disabledDate}
                            disabledTime={disabledDateTime}
                            showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                        />
                    </Form.Item>
                    <Form.Item label="交通方式" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Space>
                            <Form.Item noStyle name="transport">
                                <Select name="transport" style={{ width: 100 }} onChange={onChangeHeadle}>
                                    {
                                        transportData.map(item => {
                                            return (
                                                <Option value={item.sendName} key={item.id}>{item.sendName}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-15' onClick={(e) => modoalSH(e, 2, 's', "transport")}><PlusSquareFilled />新增</Button>
                            </Form.Item>
                        </Space>
                    </Form.Item>
                    <Form.Item label="差旅联系人" wrapperCol={{ offset: 0, span: 16 }} rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Space>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-15' onClick={(e) => modoalSH(e, 4, 's', "travelContact")}><CheckCircleFilled />选择</Button>
                            </Form.Item>
                            <Form.Item noStyle >
                                <Button type='primary' size='small' className='btn-bgc-15'><PlusSquareFilled />新建联系人</Button>
                            </Form.Item>
                        </Space>
                        <Form.Item noStyle name="travelClien">
                            <Input.TextArea style={{ marginTop: 10 }} onChange={onChangeHeadle} />
                        </Form.Item>
                    </Form.Item>
                    <Form.Item label="工作描述" rules={[{ required: true, message: 'Please input your username!' }]} name="text">
                        <WangEditor name="text" onChange={onChangeHeadle} />
                    </Form.Item>
                    <Form.Item label="附件" name="upFile" wrapperCol={{ offset: 0, span: 16 }} valuePropName="fileList"
                        getValueFromEvent={normFile}>
                        <Upload name="upFile" action="/upload.do" listType="picture">
                            <Button type='primary' size='small' className='btn-bgc-18'>选择文件</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item label="工作记录" name="record" wrapperCol={{ offset: 0, span: 16 }} >
                        <Button type='primary' size='small' className='btn-bgc-19'>工作记录</Button>
                    </Form.Item>
                    <Form.Item label="发起人" name="beginPerson" wrapperCol={{ offset: 0, span: 16 }} >
                        <Button type='primary' size='small' className='btn-bgc-20'>超级管理员</Button>
                    </Form.Item>
                </Form>
                <section>
                    {/* 新增联系人弹框 */}
                    <Modal title="新增联系人" visible={isModalVisible} onOk={handleOk} onCancel={exitHandleCancel} className='addClientPerson newAddOrder-box '
                        footer={[
                            <Button key="back" onClick={handleCancel} className='btn-bgc-13'>保存</Button>,
                            <Button key="self" onClick={exitHandleCancel} className='btn-bgc-12'> 返回</Button>]}
                    >
                        <AddClientModal saveHandleCancel={saveHandleCancel} />
                    </Modal>
                    {/*工单类型弹窗*/}
                    <Modal title="新增工单类型" visible={modalData[0].flage} onOk={handleOk} onCancel={x => colseAddOrdercata('addOrderCate')} className='addClientPerson newAddOrder-box '
                        footer={[
                            <Button key="back" onClick={x => saveAddOrdercata('addOrderCate')} className='btn-bgc-13'>保存</Button>,
                            <Button key="self" onClick={x => colseAddOrdercata('addOrderCate')} className='btn-bgc-12'> 返回</Button>]}
                    >
                        <CustomOptions send={{ sendData, headleSendData, title: { modalcate: 'addOrderCate', modalName: '工单类型' } }} />
                    </Modal>
                    {/* 交通方式 */}
                    <Modal title="交通方式" visible={modalData[1].flage} onOk={handleOk} onCancel={x => colseAddOrdercata('transport')} className='addClientPerson newAddOrder-box '
                        footer={[
                            <Button key="back" onClick={x => saveAddOrdercata('transport')} className='btn-bgc-13'>保存</Button>,
                            <Button key="self" onClick={x => colseAddOrdercata('transport')} className='btn-bgc-12'> 返回</Button>]}
                    >
                        <CustomOptions send={{ sendData: transportData, headleSendData, title: { modalcate: 'transport', modalName: '交通方式' } }} />
                    </Modal>
                    {/* 指派人员 */}
                    <Modal title="指派人员" visible={modalData[2].flage} onOk={handleOk} onCancel={x => colseAddOrdercata('assigned')} className='fastSelect newAddOrder-box '
                        footer={[
                            <Button key="back" onClick={x => saveAddOrdercata('assigned')} className='btn-bgc-13'>保存</Button>,
                            <Button key="self" onClick={x => colseAddOrdercata('assigned')} className='btn-bgc-12'> 返回</Button>]}
                    >
                        <FastSelect sendData={{ assignedData, cateName: 'assigned', headleSendData }} />
                    </Modal>
                    {/* TODO:差旅联系人 */}
                    <Modal title="差旅联系人" visible={modalData[3].flage} onOk={handleOk} onCancel={x => colseAddOrdercata('travelContact')} className='fastSelect newAddOrder-box '
                        footer={[
                            <Button key="back" onClick={x => saveAddOrdercata('travelContact')} className='btn-bgc-13'>保存</Button>,
                            <Button key="self" onClick={x => colseAddOrdercata('travelContact')} className='btn-bgc-12'> 返回</Button>]}
                    >
                        <FastSelect sendData={{ assignedData, cateName: 'travelContact', headleSendData }} />
                    </Modal>
                </section>
            </div>
        </div>
    );
}

export default AddOrderInfo;
